/**
 * @author 0283000115
 * @date 2017年9月27日-下午4:12:08
 */
package com.zte.claa.inficombo.csa.app.util;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.ShortBufferException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author 0283000115
 *
 */
public class AesCmac {
	private static final Logger logger = LoggerFactory.getLogger(AesCmac.class);			
	private static final IvParameterSpec ZERO_IV = new IvParameterSpec(new byte[16]); 
	private static final byte CONSTANT = (byte) 0x87;
    private static final int BLOCK_SIZE = 16;

    private int macLength;
    private Cipher aesCipher;

    private byte[] buffer;
    private int bufferCount;

    private byte[] k1;
    private byte[] k2;

    public AesCmac() throws NoSuchAlgorithmException {
        this(BLOCK_SIZE);
    }

    public AesCmac(int length) throws NoSuchAlgorithmException {
        if (length > BLOCK_SIZE) {
        	logger.error("AES CMAC maximum length is " + BLOCK_SIZE);
            throw new NoSuchAlgorithmException("AES CMAC maximum length is " + BLOCK_SIZE);
        }

        try {
            macLength = length;
            aesCipher = Cipher.getInstance("AES/CBC/NOPADDING");
            buffer = new byte[BLOCK_SIZE];
        } catch (NoSuchPaddingException nspe) {
            logger.error("AesCmac init failed: "+nspe.getMessage(), nspe);
        }
    }

    private byte[] doubleSubKey(byte[] k) {
        byte[] ret = new byte[k.length];
        boolean firstBitSet = ((k[0]&0x80) != 0);
        for (int i=0; i<k.length; i++) {
            ret[i] = (byte) (k[i] << 1);
            if (i+1 < k.length && ((k[i+1]&0x80) != 0)) {
                ret[i] |= 0x01;
            }
        }
        if (firstBitSet) {
            ret[ret.length-1] ^= CONSTANT;
        }
        return ret;
    }

    /**
     * 初始化
     * 
     * @param key
     * @param enMode
     * @throws Exception
     */
    public final void init(Key key, int enMode) throws Exception {
        if (!(key instanceof SecretKeySpec)) {
            throw new InvalidKeyException("Key is not of required type SecretKey.");
        }
        if (!((SecretKeySpec)key).getAlgorithm().equals("AES")) {
            throw new InvalidKeyException("Key is not an AES key.");
        }
        aesCipher.init(enMode, key, ZERO_IV);

        // First calculate k0 from zero bytes
        byte[] k0 = new byte[BLOCK_SIZE];
        try {
            aesCipher.update(k0, 0, k0.length, k0, 0);
        } catch (ShortBufferException sbe) {}

        // Calculate values for k1 and k2
        k1 = doubleSubKey(k0);
        k2 = doubleSubKey(k1);

        aesCipher.init(enMode, key, ZERO_IV);
        bufferCount = 0;
    }

    /**
     * 
     * @param b
     */
    public final void updateByte(byte b) {
        updateBlock(new byte[] { b });
    }

    /**
     * 
     * @param data
     */
    public final void updateBlock(byte[] data) {
        int currentOffset = 0;

        if (data.length < BLOCK_SIZE-bufferCount) {
            System.arraycopy(data, 0, buffer, bufferCount, data.length);
            bufferCount += data.length;
            return;
        } else if (bufferCount > 0) {
            System.arraycopy(data, 0, buffer, bufferCount, BLOCK_SIZE-bufferCount);
            try {
                aesCipher.update(buffer, 0, BLOCK_SIZE, buffer, 0);
            } catch (ShortBufferException sbe) {
            	logger.error("updateBlock failed: "+sbe.getMessage(), sbe);
            }
            currentOffset += BLOCK_SIZE-bufferCount;
            bufferCount = 0;
        }

        // Transform all the full blocks in data
        while (currentOffset+BLOCK_SIZE < data.length) {
            try {
                aesCipher.update(data, currentOffset, BLOCK_SIZE, buffer, 0);
            } catch (ShortBufferException sbe) {
            	logger.error("updateBlock failed: "+sbe.getMessage(), sbe);
            }
            currentOffset += BLOCK_SIZE;
        }

        // Save the leftover bytes to buffer
        if (currentOffset != data.length) {
            System.arraycopy(data, currentOffset, buffer, 0, data.length-currentOffset);
            bufferCount = data.length-currentOffset;
        }
    }

    /**
     * 
     * @return
     */
    public final byte[] doFinal() {
        byte[] subKey = k1;
        if (bufferCount < BLOCK_SIZE) {
            // Add padding and XOR with k2 instead
            buffer[bufferCount] = (byte) 0x80;
            for (int i=bufferCount+1; i<BLOCK_SIZE; i++){
                buffer[i] = (byte) 0x00;
            }
            subKey = k2;
        }
        for (int i=0; i<BLOCK_SIZE; i++) {
            buffer[i] ^= subKey[i];
        }

        // Calculate the final CMAC calue
        try {
            aesCipher.doFinal(buffer, 0, BLOCK_SIZE, buffer, 0);
        }
        // These should never happen because we pad manually
        catch (ShortBufferException sbe) {
        	logger.error("doFinal failed: "+sbe.getMessage(), sbe);
        }
        catch (IllegalBlockSizeException ibse) {
        	logger.error("doFinal failed: "+ibse.getMessage(), ibse);
        }
        catch (BadPaddingException ibse) {
        	logger.error("doFinal failed: "+ibse.getMessage(), ibse);
        }
        bufferCount = 0;

        byte[] mac = new byte[macLength];
        System.arraycopy(buffer, 0, mac, 0, macLength);
        return  mac;
    }

    /**
     * 
     * @param data
     * @return
     */
    public final byte[] calculateHash(byte[] data) {
        updateBlock(data);
        return doFinal();
    }
    
    /** 
     * 将二进制转换成16进制 
     * @method parseByte2HexStr 
     * @param buf 
     * @return 
     * @throws  
     * @since v1.0 
     */  
    public static String parseByte2HexStr(byte buf[]){  
        StringBuffer sb = new StringBuffer();  
        for(int i = 0; i < buf.length; i++){  
            String hex = Integer.toHexString(buf[i] & 0xFF);  
            if (hex.length() == 1) {  
                hex = '0' + hex;  
            }  
            sb.append(hex.toUpperCase());  
        }  
        return sb.toString();  
    }  
      
    /** 
     * 将16进制转换为二进制 
     * @method parseHexStr2Byte 
     * @param hexStr 
     * @return 
     * @throws  
     * @since v1.0 
     */  
    public static byte[] parseHexStr2Byte(String hexStr){  
        if(hexStr.length() < 1)  
            return null;  
        byte[] result = new byte[hexStr.length()/2];  
        for (int i = 0;i< hexStr.length()/2; i++) {  
            int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);  
            int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);  
            result[i] = (byte) (high * 16 + low);  
        }  
        return result;  
    }  
    
    /**
     * 根据eui和kiid计算update byte[]
     * 
     * @param eui
     * @param kiid
     * @return
     */
    public static byte[] genUpdateBytes(String eui, String kiid){
		byte[] ret = new byte[16];
		for(int i=0; i<ret.length; i++){
			ret[i] = 0;
		}
		// eui = 0200000000001211 
		// kiid= 11223344
		// 目标顺序：kiid-eui 00000000000011223344-0200000000001211
		byte[] euiBs = parseHexStr2Byte(eui);
		byte[] kiidBs = parseHexStr2Byte(kiid);
		
		for(int i=0;i<kiidBs.length;i++)
		{
			ret[7-i] = (byte)(kiidBs[kiidBs.length-1-i] & 0xFF);
		}
		//按大字节序存放EUI
		for(int i=0;i<8;i++)
		{
			ret[8+i] = (byte)(euiBs[i] & 0xFF);
		}
		// System.out.println("update: "+parseByte2HexStr(ret));
		return ret;
	}
    
    /**
     * test
     * 
     * @param args
     */
    public static void main1(String[] args){
		try {
			String eui = "0200000000001211";
	    	String kiid = "11223344";
	    	byte[] input = AesCmac.genUpdateBytes(eui, kiid);
	    	System.out.println("input="+input.length);
	    	
	    	// String cKey = "12345678901234561234567890123456";
	        // 需要加密的字串
	        String cSrc =  "908711dd739c44e89f87b98f3b9c4557";  //""1111122222333334";
	        System.out.println(cSrc);
	    	
			byte[] masterKey = parseHexStr2Byte("12345678901234561234567890123456");
			// byte[] masterKey = {0x12,0x34,0x56,0x78,(byte)0x90,0x12,0x34,0x56,0x12,0x34,0x56,0x78,(byte)0x90,0x12,0x34,0x56};
			// byte[] input = { (byte)0x90, (byte)0x87, 0x11, (byte)0xdd, 0x73, (byte)0x9c, 0x44, (byte)0xe8, (byte)0x9f, (byte)0x87, (byte)0xb9, (byte)0x8f, 0x3b, (byte)0x9c, 0x45, 0x57 };
			
			// 加密.
			AesCmac mac = null;
		    mac = new AesCmac();
		    SecretKey key = new SecretKeySpec(masterKey, "AES");
		    mac.init(key, Cipher.ENCRYPT_MODE);  //set master key
		    mac.updateBlock(input); //given input
		    // for (byte b: input) System.out.print(" "+b);
		    byte[] ret = mac.doFinal();		    
		    System.out.println("After dofinal:\n"+parseByte2HexStr(ret));	
		    byte[] sSrcBs = parseHexStr2Byte(cSrc);
		    byte[] encodeRet = new byte[16];
		    for (int i=0; i<16; i++)
			{
		    	encodeRet[i] = (byte)(sSrcBs[i]^ret[i]);
			}
		    System.out.println("After encrypt:\n"+parseByte2HexStr(encodeRet));		    
		    System.out.println("target: \n"+"c119a3602b2c911120fed76035dee546".toUpperCase());
		    
		    // 解密（同样也是加密过程）
		    AesCmac mac2 = new AesCmac();
		    // SecretKey key = new SecretKeySpec(masterKey, "AES");
		    mac2.init(key, Cipher.ENCRYPT_MODE);  //set master key
		    mac2.updateBlock(input); //given input
		    byte[] ret2 = mac2.doFinal();		    
		    System.out.println("After dofinal:\n"+parseByte2HexStr(ret));	
		    byte[] decodeRet = new byte[16];
		    for (int i=0; i<16; i++)
			{
		    	decodeRet[i] = (byte)(encodeRet[i]^ret2[i]);
			}
		    System.out.println("After decrypt:\n"+parseByte2HexStr(decodeRet));	
		}catch(Exception e){
    		e.printStackTrace();
    	}
    }
}
